// 对ip进行管理，主要是限制每个ip允许的连接数量
package ipmanager

import (
	"net"
)

func GetUint32IP(c net.Conn) uint32 {
	return ip2uint32(GetConnIP4(c))
}

func GetConnIP4(c net.Conn) net.IP {
	addr := c.RemoteAddr()
	ipAddr, ok := addr.(*net.TCPAddr)
	if !ok {
		return net.IPv4zero
	}
	return ipAddr.IP.To4()
}

func AcquirePerIPConn(conn net.Conn, ip uint32, counter *PerIPConnCounter) *PerIPConn {
	v := counter.pool.Get()
	if v == nil {
		v = &PerIPConn{
			perIPConnCounter: counter,
		}
	}
	c := v.(*PerIPConn)
	c.Conn = conn
	c.ip = ip
	return c
}

func ip2uint32(ip net.IP) uint32 {
	if len(ip) != 4 {
		return 0
	}
	return uint32(ip[0])<<24 | uint32(ip[1])<<16 | uint32(ip[2])<<8 | uint32(ip[3])
}

func uint322ip(ip uint32) net.IP {
	b := make([]byte, 4)
	b[0] = byte(ip >> 24)
	b[1] = byte(ip >> 16)
	b[2] = byte(ip >> 8)
	b[3] = byte(ip)
	return b
}
